package _02_linked_list.exerc.remove;

import _02_linked_list.exerc.ListNode;
import org.junit.Test;

/**
 * @author: mornd
 * @dateTime: 2023/6/2 - 21:16
 * 给定一个值 val，删除单向链表中包含该值的所有节点
 */
public class MyTest {

    static ListNode init(int[] arr) {
        ListNode head = null;
        ListNode tail = null;
        for (int v : arr) {
            ListNode t = new ListNode(v);
            if(head == null) {
                head = tail = t;
            } else {
                tail.next = t;
                tail = t;
            }
        }
        return head;
    }

    @Test
    public void test() {
        ListNode list = init(new int[]{1, 2,3});
        System.out.println(list);
        System.out.println(foo2(list, 2));
    }

    // 方法1
    ListNode foo1(ListNode node, int val) {
        ListNode t = new ListNode();
        t.next = node;
        ListNode p1 = t;
        ListNode p2;
        while ((p2 = p1.next) != null) {
            if(p2.val == val) {
                p1.next = p2.next;
            } else {
                p1 = p1.next;
            }
        }
        return t.next;
    }

    // 方法2 使用递归删除
    ListNode foo2(ListNode node, int val) {
        if(node == null) {
            return null;
        }

        ListNode last = foo2(node.next, val);
        if(node.val == val) {
            return last;
        } else {
            node.next = last;
            return node;
        }
    }
}
